<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
            <el-form-item label="分类名称" prop="className" label-width="120px">
               <el-input
                  v-model="queryParams.className"
                  placeholder="请输入分类名称"
                  clearable
                   style="width: 260px"
                  @keyup.enter="handleQuery"
                  @clear="handleQuery"
                  @input="handleInput"
               />
            </el-form-item>
            <el-form-item>
               <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            </el-form-item>
      </el-form>
     <el-table
        v-if="refreshTable"
        v-loading="loading"
        :data="menuList"
        row-key="id"
        :default-expand-all="isExpandAll"
        :indent="30"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"  >
        <el-table-column prop="className" label="分类名称"  align="left" width="300"></el-table-column>
        <el-table-column prop="groupCode" label="父级节点编码" align="center"></el-table-column>
        <el-table-column label="操作" align="center" width="210" class-name="small-padding fixed-width">
           <template #default="scope" >
              <el-button link type="primary" v-if="scope.row.groupCode != -1" icon="Plus" @click="handleAdd(scope.row)" >新增</el-button>
              <el-button link type="primary" v-if="scope.row.groupCode != -1" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
              <el-button link type="danger"  v-if="scope.row.groupCode != -1" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
           </template>
        </el-table-column>
     </el-table>

     <!-- 添加或修改菜单对话框 -->
     <el-dialog :title="title" v-model="open" width="680px" append-to-body>
        <el-form ref="menuRef" :model="form" :rules="rules" label-width="100px">
           <el-row> 
              <el-col :span="24">
                 <el-form-item label="上级菜单" prop="groupCode">
                    <el-tree-select
                       v-model="form.groupCode"
                       :data="menuOptions"
                       :props="{ value: 'classCode', label: 'className', children: 'children' }"
                       value-key="classCode"
                       placeholder="选择上级菜单"
                       check-strictly
                    />
                 </el-form-item>
              </el-col>
              <el-col :span="24">
                 <el-form-item label="分类名称" prop="className">
                    <el-input v-model="form.className" placeholder="请输入分类名称" />
                 </el-form-item>
              </el-col>
            </el-row> 
        </el-form>
        <template #footer>
           <div class="dialog-footer">
              <el-button type="primary" @click="submitForm">确 定</el-button>
              <el-button @click="cancel">取 消</el-button>
           </div>
        </template>
     </el-dialog>
  </div>
</template>

<script setup name="Menu">
import { addMenu, delMenu, getMenu, listMenu, updateMenu } from "@/api/system/menu";
import SvgIcon from "@/components/SvgIcon";
import IconSelect from "@/components/IconSelect";

const { proxy } = getCurrentInstance();
// const { sys_show_hide, sys_normal_disable } = proxy.useDict("sys_show_hide", "sys_normal_disable");

const menuList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const title = ref("");
const menuOptions = ref([]);
const isExpandAll = ref(false);
const refreshTable = ref(true);
const iconSelectRef = ref(null);
const value = ref('')
const options = ref([])


const data = reactive({
 form: {},
 queryParams: {
  className: "",
 },
 rules: {
   groupCode: [{ required: true, message: "请选择上级菜单", trigger: "blur" }],
   className: [{ required: true, message: "分类名称不能为空", trigger: "blur" }],
  },
});

const { queryParams, form, rules } = toRefs(data);

// 切换系统
function changeValue(val){
 value.value = val;
 queryParams.value.tenantID = val;
 getList();
} 


/** 查询菜单列表 */
async function getList() {
  proxy.quote_API.GetClassCodeByGroup({
    ...queryParams.value,
   }).then(response => {
        response.data.forEach(element => {
           element.children = [];
        });
        // groupCode 是上级节点 id，可理解为父节点字段 默认 'parentId'
        // classCode 是当前节点 id，可理解为子节点字段 默认 'id' 用来匹配上个groupCode
       menuList.value = proxy.handleTree(response.data,'classCode','groupCode');
       loading.value = false;
   });
}
/** 查询菜单下拉树结构 */
function getTreeselect() {
 menuOptions.value = [];
 proxy.quote_API.GetClassCodeByGroup({
    ...queryParams.value,
   }).then(response => {
      response.data.forEach(element => {
        element.children = []
       })
      menuOptions.value = proxy.handleTree(response.data,'classCode','groupCode');
      
   });
}

// 处理值变化的方法
const handleChange = (value) => {
 if (Number.isInteger(value)) {
   if (value < 0) {
     form.value.reOrder = 1;
   } else if (value > 100) {
     form.value.reOrder = 100;
   }
 } else {
   // 如果不是整数，恢复到上一个有效值
   form.value.reOrder = Math.round(form.value.reOrder);
 }
}
/** 取消按钮 */
function cancel() {
 open.value = false;
 reset();
}

/** 表单重置 */
function reset() {
 form.value = {
   id: null,
   groupCode: -1,
   className: "",
 };
 proxy.resetForm("menuRef");
}

/** 展示下拉图标 */
function showSelectIcon() {
 iconSelectRef.value.reset();
}

/** 选择图标 */
function selected(name) {
 form.value.reIcon = name;
}

// 输入时触发的防抖处理函数
let timer = null;
function handleInput() {
   clearTimeout(timer);
   timer = setTimeout(handleQuery, 300);
}

/** 搜索按钮操作 */
function handleQuery() {
 getList();
}

/** 重置按钮操作 */
function resetQuery() {
 proxy.resetForm("queryRef");
 handleQuery();
}

/** 新增按钮操作 */
function handleAdd(row) {
 reset();
 getTreeselect();
 if (row != null && row.classCode) {
  form.value.groupCode = row.classCode;
 } else {
   form.value.reParetntID = -1;
 }
 open.value = true;
 title.value = "添加分类";
}

/** 展开/折叠操作 */
function toggleExpandAll() {
 refreshTable.value = false;
 isExpandAll.value = !isExpandAll.value;
 nextTick(() => {
   refreshTable.value = true;
 });
}

/** 修改按钮操作 */
async function handleUpdate(row) {
 reset();
 await getTreeselect();
 Object.keys(form.value).forEach(key => {
   form.value[key] = row[key];
 });
 console.log(form.value);
 
 open.value = true;
 title.value = "修改分类";
}

/** 提交按钮 */
function submitForm() {
 proxy.$refs["menuRef"].validate(valid => {
   if (valid) {
     if (form.value.id) {
        proxy.quote_API.UpdateClassCode({
          ...form.value,
        }).then(response => {
           proxy.$modal.msgSuccess("编辑成功");
           open.value = false;
           getList();
        });
     } else {
        proxy.quote_API.AddClassCode({
           ...form.value,
        }).then(response => {
           proxy.$modal.msgSuccess("新增成功");
           open.value = false;
           getList();
        });
     }
   }
 });
}

/** 删除按钮操作 */
function handleDelete(row) {
  proxy.$modal.confirm('是否确认删除分类"' + row.className + '"的数据项?').then(function () {
   proxy.quote_API.DeleteClassCode({id:row.id}).then(response => {
     getList();
     proxy.$modal.msgSuccess("删除成功");
   });
 })
}

getList();

</script>

<style lang="scss" scoped>
::v-deep(.el-select__icon){
  color: #409EFF;
}
</style>
